Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

[productId].js 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. const Product = require('../../../models/product');
  2. import dbConnect from '../../../utils/helpers/dbHelpers';
  3. async function handler(req, res) {
  4. const { method } = req;
  5. await dbConnect();
  6. switch (method) {
  7. case 'GET': {
  8. try {
  9. const productId = req.query.productId;
  10. const product = await Product.findOne({ customID: productId });
  11. if (!product) {
  12. throw new Error('The product with this id does not exist!');
  13. }
  14. const similarProducts = await Product.find({
  15. category: product.category,
  16. customID: { $ne: product.customID },
  17. });
  18. const shuffled = similarProducts
  19. .sort(() => 0.5 - Math.random())
  20. .slice(0, 3);
  21. res.status(200).json({
  22. message: 'The product you requested was fetched successfully.',
  23. product,
  24. similarProducts: shuffled,
  25. });
  26. } catch (error) {
  27. res.status(400).json({ message: error.message });
  28. }
  29. break;
  30. }
  31. default:
  32. res.status(405).json({ message: 'Method not allowed' });
  33. break;
  34. }
  35. }
  36. export default handler;